import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, getYear, getPayCycleDom } from 'lib/fun'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const { RangePicker } = DatePicker;
const Option = Select.Option;

class Filter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      selectedCode: '',
      selectedCategory: '',
      projectCate: [],
    }
  }

  componentDidMount(){
    // this.loadArea();
    if(this.props.common.user&&this.props.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: this.props.common.user.user.areaId,
          areaName: this.props.common.user.user.areaName,
        }]
      });
    }
    this.loadProjectCategory();
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.common.user&&nextProps.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: nextProps.common.user.user.areaId,
          areaName: nextProps.common.user.user.areaName,
        }]
      });
    }
  }

  loadProjectCategory = ()=>{
    var self = this;
    Ajax({
      url: '/projectCate/list',
      success: function(data){
        var projectCate = []
        const loop = (data) => {
          data.forEach((item) => {
            const { projectCategoryId, projectCategoryCode, projectCategoryName } = item;
            projectCate.push({
              projectCategoryId, 
              projectCategoryCode, 
              projectCategoryName
            });
            if(item.children&&item.children.length > 0){
              loop(item.children);
            }
          });
        };
        loop(data);
        
        self.setState({
          projectCate: projectCate
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadProject = (id)=>{
    var self = this;
    if(!id){
      return
    }
    var selected = findRowData(self.state.projectCate, id, 'projectCategoryId');
    if(selected&&selected.children){
      return 
    }else{
      Ajax({
        url: '/project/list',
        data: {
          projectCategoryId: id,
          perPage: 10000
        },
        success: function(data){
          var projectCate = self.state.projectCate;
          if(projectCate&&projectCate.length > 0){
            projectCate = getNewTreeData(projectCate, id, data.list, 'projectCategoryId');
          }
          self.setState({
            projectCate: projectCate
          });
        },
        error: function(error){
          message.error(error);
        }
      });
    }
  }

  loadArea = (treeNode)=>{
    console.log('load area');
    var self = this;
    var selected = findRowData(self.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleSearch = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      values.state = values.state?[values.state]:undefined;
      self.props.handleFilter(values);
    });
  }

  selectChange = (value)=>{
    this.setState({
      selectedCode: value
    });
    this.props.form.setFieldsValue({
      subsidyCount: ""
    });
  }

  changeCategory = (value)=>{
    this.setState({
      selectedCategory: value
    });
    var find = _.find(this.state.projectCate, (item)=>{
      return item.projectCategoryId == value
    })
    if(!(find&&find.children)){
      this.loadProject(value);
    }
    this.props.form.setFieldsValue({
      projectId: ""
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    const years = getYear();

    const { payCycleCode } = this.props.config;
    const projectRegisterEn = this.props.common.projectRegisterEn||[]

    let projectList = [];
    var find = _.find(this.state.projectCate, (item)=>{
      return item.projectCategoryId == this.state.selectedCategory
    })
    if(find&&find.children){
      projectList = find.children
    }
    return (<Form
          horizontal
          className="ant-advanced-search-form"
          onSubmit={this.handleSearch}
        >
          <Row gutter={20}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="补贴登记区划">
                {getFieldDecorator("areaId")(
                  
                    this.props.treeData?<Select
                      allowClear
                      size="default"
                      dropdownMatchSelectWidth={false}
                    >
                      {
                        (this.props.treeData||[]).map(function(obj){
                          return (<Option key={obj.areaId+""} value={ obj.areaId+"" }>{ obj.areaName }</Option>)
                        })
                      }
                    </Select>:<TreeSelect
                      allowClear
                      size="default"
                      loadData={ this.loadArea }
                      dropdownMatchSelectWidth={false}
                    >
                      { treeNodes }
                    </TreeSelect>
                  
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="项目分类">
                {getFieldDecorator("projectCategoryId")(
                  <Select
                    allowClear
                    size="default"
                    onChange={this.changeCategory}
                    dropdownMatchSelectWidth={false}
                  >
                  {
                    this.state.projectCate.map((obj)=>{
                      return (<Option key={obj.projectCategoryId}>{ obj.projectCategoryName }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="补贴项目">
                {getFieldDecorator("projectId")(
                  <Select
                    allowClear
                    size="default"
                    dropdownMatchSelectWidth={false}
                  >
                  {
                    projectList.map((obj)=>{
                      return (<Option key={obj.projectId}>{ obj.projectName }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="发放年度">
                {getFieldDecorator("year")(
                  <Select
                    allowClear
                    size="default"
                  >
                  {
                    years.map((obj)=>{
                      return (<Option key={obj}>{ obj }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="发放周期">
                {getFieldDecorator("payCycleCode")(
                  <Select
                    allowClear
                    size="default"
                    onChange={this.selectChange}
                  >
                  {
                    (payCycleCode||[]).map(function(obj){
                      return (<Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="发放次数">
                {getFieldDecorator("subsidyCount")(
                  <Select
                    allowClear
                    size="default"
                  >
                  {
                    this.state.selectedCode?getPayCycleDom(this.state.selectedCode):null
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="状态">
                {getFieldDecorator("state")(
                  <Select
                    allowClear
                    size="default"
                    dropdownMatchSelectWidth={false}
                  >
                  {
                    (projectRegisterEn||[]).map(function(obj){
                      return (<Option key={obj.code} value={ obj.code+"" }>{ obj.mean }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            
            <Col>
              <div className="btn-box">
                <Button type="primary" htmlType="submit">查询</Button>
              </div>
            </Col>
          </Row>
        </Form>);
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

module.exports = connect(mapStateToProps)(Form.create()(Filter))